﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;

namespace src.Helper
{
    public class HttpHelper
    {
        private HttpClient _httpClient;
        private string _baseAddress;

        public HttpHelper()
        {
            this._httpClient = new HttpClient();
        }
        public HttpHelper(string ipAddress)
        {
            this._baseAddress = ipAddress;
            this._httpClient = new HttpClient { BaseAddress = new Uri(this._baseAddress) };
        }
        public string Get(Dictionary<string, string> parameters, string requestUri)
        {
            if (parameters != null)
            {
                var strParam = string.Join("&", parameters.Select(o => o.Key + "=" + o.Value));
                requestUri = string.Concat(ConcatURL(requestUri), '?', strParam);
            }
            else
            {
                requestUri = ConcatURL(requestUri);
            }
            var result = _httpClient.GetStringAsync(requestUri);
            return result.Result;
        }

        public string GetStr(string requestUri)
        {
            var result = _httpClient.GetStringAsync(requestUri);
            return result.Result;
        }

        public T Get<T>(Dictionary<string, string> parameters, string requestUri) where T : class
        {
            string jsonString = Get(parameters, requestUri);
            if (string.IsNullOrEmpty(jsonString))
                return null;

            return JsonConvert.DeserializeObject<T>(jsonString);
        }

        public string Post(object entity, string requestUri)
        {
            string request = string.Empty;
            if (entity != null)
            {
                request = JsonConvert.SerializeObject(entity);
            }
            HttpContent httpContent = new StringContent(request);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return Post(requestUri, httpContent);
        }

        public string PostDicObj(Dictionary<string, object> para, string requestUri)
        {
            Dictionary<string, string> temp = new Dictionary<string, string>();
            foreach (var item in para)
            {
                if (item.Value != null)
                {
                    if (item.Value.GetType().Name.ToLower() != "string")
                    {
                        temp.Add(item.Key, JsonConvert.SerializeObject(item.Value));
                    }
                    else
                    {
                        temp.Add(item.Key, item.Value.ToString());
                    }
                }
                else
                {
                    temp.Add(item.Key, "");
                }
            }

            return PostDic(temp, requestUri);
        }

        public string PostDic(Dictionary<string, string> temp, string requestUri)
        {
            HttpContent httpContent = new FormUrlEncodedContent(temp);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            return Post(requestUri, httpContent);
        }

        public string PostStr(string str, string requestUri)
        {
            HttpContent httpContent = new StringContent(str);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return Post(requestUri, httpContent);
        }

        private string Post(string requestUrl, HttpContent content)
        {
            var result = _httpClient.PostAsync(ConcatURL(requestUrl), content);
            return result.Result.Content.ReadAsStringAsync().Result;
        }

        public string PostFile(string requestUrl, string filePath)
        {
            string boundary = DateTime.Now.Ticks.ToString("X");
            MultipartFormDataContent content = new MultipartFormDataContent(boundary);
            byte[] data = File.ReadAllBytes(filePath);
            content.Headers.Remove("Content-Type");
            content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
            var contentByte = new ByteArrayContent(data);
            content.Add(contentByte);
            contentByte.Headers.TryAddWithoutValidation("Content-Disposition", $"form-data; name=\"media\";filename=\"{Path.GetFileName(filePath)}\"");
            var result = _httpClient.PostAsync(requestUrl, content).Result.Content.ReadAsStringAsync();
            return result.Result;
        }
        private string ConcatURL(string requestUrl)
        {
            if (string.IsNullOrWhiteSpace(_baseAddress))
            {
                return new Uri(requestUrl).OriginalString;
            }
            return new Uri(_httpClient.BaseAddress, requestUrl).OriginalString;
        }
    }
}
